/**
 * 
 */
package fr.cephb.servlet;


import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.events.EndElement;


/**
 * implementation of {@link AbstractTabularExportFilter}
 * for comma separated values
 */
public class CSVExportFilter extends AbstractTabularExportFilter
	{
	/** return true if req.getParameter(PARAM)=='csv' */ 
	@Override
	protected boolean isFiltering(HttpServletRequest req)
			throws ServletException
		{
		
		boolean b= "csv".equalsIgnoreCase(req.getParameter(PARAM));
		return b;
		}
	
	@Override
	protected void export(File content, HttpServletRequest req,
			HttpServletResponse res) throws IOException, ServletException {
		res.setContentType("text/plain");
		super.export(content, req, res);
		}
	
	@Override
	public void endCell(HttpServletRequest req, HttpServletResponse res,EndElement e, int row,
			int col, String content) throws IOException, ServletException {
		if(col>0) res.getWriter().print('\t');
		res.getWriter().print(content.trim().replace("\n", "\\n").replace("\t", "\\t"));
		}
	
	@Override
	public void endRow(HttpServletRequest req, HttpServletResponse res, int line)
			throws IOException, ServletException {
		res.getWriter().print('\n');
		}

	@Override
	public void endTable(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		res.getWriter().flush();
		}
	
	}
